package com.yunsoft.gateway.interceptor.handler;

import com.fld.central.common.model.code.BaseCode;
import com.fld.central.common.model.exception.SpiException;
import com.yunsoft.gateway.annotation.Internal;
import com.yunsoft.gateway.annotation.WebInterceptor;
import com.yunsoft.gateway.utils.RequestUtils;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;

/**
 * 内网访问拦截器
 * @author summerrains
 *
 */
@WebInterceptor(name = "internalHandlerInterceptor", pathPatterns = { "/**" }, order = 1)
public class InternalHandlerInterceptor extends BaseHandlerInterceptor {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(InternalHandlerInterceptor.class);

	private static final List<String> IP_LIST = new ArrayList<String>();
	static {
		IP_LIST.add("127.0.0.1");
		IP_LIST.add("localhost");
		IP_LIST.add("172.15");
		IP_LIST.add("172.18");
	}

	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		if (!(handler instanceof HandlerMethod)) {
			return true;
		}
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        // 获取方法上的注解
        Internal internal = handlerMethod.getMethod().getAnnotation(Internal.class);
        // 如果方法上的注解为空 则获取类的注解
        if (internal == null) {
        	internal = handlerMethod.getMethod().getDeclaringClass().getAnnotation(Internal.class);
        }
        // 如果标记了注解，则判断权限
        if (internal != null) {
            // redis或数据库 中获取该用户的权限信息 并判断是否有权限
        	String ips = internal.ips();
        	checkIpAddress(request,ips);
        }
        return true;
	}
	
	private void checkIpAddress(HttpServletRequest request,String ips) throws SpiException {
		
		String realIp = RequestUtils.getIpAddress(request);
		LOGGER.info("client ip:"+realIp);
		//
		if(StringUtils.isEmpty(realIp)) {
			throw new SpiException(BaseCode.ERROR,"仅限内部访问，client ip is null");
		}
		boolean exists = false;
		//默认IP
		for (String ip : IP_LIST) {
			if(realIp.indexOf(ip) == 0) {
				exists = true;
				break;
			}
		}
		//自定义IP
		if(!StringUtils.isEmpty(ips)) {
			String[] ipArr = ips.split(",");
			for (String ip : ipArr) {
				if(realIp.indexOf(ip) == 0) {
					exists = true;
					break;
				}
			}
		}
		//
		if(!exists) {
			throw new SpiException(BaseCode.ERROR,"仅限内部访问，client ip:"+realIp);
		}

	}
	
}
